using System;
using System.Collections.Generic;

namespace DA.AnimGraph.Editor {
    internal class ServiceManager {
        Dictionary<Type, Service> services = new();

        public void AddService<T>(object provider, bool canCover = false) where T : Service {
            if (!services.ContainsKey(typeof(T))) {
                var service = Activator.CreateInstance<T>();
                service.provider = provider;
                services.Add(typeof(T), service);
            } else if (canCover) {
                var service = Activator.CreateInstance<T>();
                service.provider = provider;
                services[typeof(T)] = service;
            } else {
                D.E($"注册服务失败，已经存在服务且不允许覆盖: {typeof(T)}");
            }
        }
        public T GetService<T>() where T : Service {
            if (services.TryGetValue(typeof(T), out var service)) {
                return service as T;
            }
            return null;
        }
        public void RemoveService<T>(object provider) where T : Service {
            if (services.TryGetValue(typeof(T), out var service)) {
                if (service.provider == provider) {
                    services.Remove(typeof(T));
                }
            }
        }

        public void Clear() {
            services?.Clear();
        }
    }


    internal abstract class Service {
        public object provider;
    }
}
